package com.DataDecrypt;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;


public class DataDecrypt {

    /**
     * 对密文进行解密
     *
     * @param text 密文
     * @param sessionKey session2Code接口获取到的sessionKey
     * @param iv 向量
     * @return 解密后的明文
     */
    public String decrypt(String text, String sessionKey, String iv) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(Base64.decodeBase64(sessionKey), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(Base64.decodeBase64(iv));

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] decrypted = cipher.doFinal(Base64.decodeBase64(text));
        byte[] bytes = PKCS7Decoder.decode(decrypted);
        return new String(bytes, StandardCharsets.UTF_8);
    }
}
